package com.thinkingcoder.tcconfig.server.config;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.servlet.http.HttpServletRequest;

public class AsyncWebMvcConfig implements WebMvcConfigurer {

    @Bean
    public ThreadPoolTaskExecutor asyncWebMvcTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("async-web-mvc-");
        executor.initialize();
        return executor;
    }

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setTaskExecutor(asyncWebMvcTaskExecutor());
        configurer.setDefaultTimeout(30000L);
    }

    @ControllerAdvice
    public static class AsyncControllerAdviceExceptionHandler {
        @ResponseStatus(HttpStatus.NOT_MODIFIED)
        @ResponseBody
        @ExceptionHandler({AsyncRequestTimeoutException.class})
        public void handlerAsyncRequestTimeoutException(AsyncRequestTimeoutException e, HttpServletRequest request) {
            System.out.println("AsyncRequestTimeoutException");
        }
    }
}
